package com.fingard.dsp.bank.directbank.hfrcb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.directbank.fngrd01.util.StringHelper;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.Date;

/**
 * Created by F on 2020/2/4.
 */
public class HFRCB01Transaction extends HFRCB01Base implements ITransaction {
    int qrySuccNum =0;
    int qryFailNum =0;
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo ="";
        retAtsTrans.writeStart();

        try{
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while(tmpIntDateFrom<=tmpIntDateTo && StringHelper.isNullOrEmpty(tmpRespCode)){
                WriteBankLogLn("****************************************************************************\r\n");
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                if(DateHelper.compareMonth(tmpCalendarFrom,tmpCalendarTo)==-1){
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH,tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                }else{
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                 qryHisTrans(tmpCalendarFrom.getTime(),tmpClndrStepTo.getTime(),p_req7516,retAtsTrans);

                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        }catch (Exception ex){
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            ex.printStackTrace();
        }
        if ("-1".equals(tmpRespCode)) {
            retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
            retAtsTrans.writeStart();//写返回ATS的统一头部信息
            retAtsTrans.writeRespCode(tmpRespCode);
            retAtsTrans.writeRespInfo(tmpRespInfo);
        }else if (qryFailNum==0&&retAtsTrans.getWrittenRdCount()==0) {
            retAtsTrans.writeRespCode("0");
            retAtsTrans.writeRespInfo("交易为空");
        }else if (qrySuccNum==0&&qryFailNum!=0&&retAtsTrans.getWrittenRdCount()==0) {
            retAtsTrans.writeRespCode("-1");
            retAtsTrans.writeRespInfo("查询失败,请检查dsp日志查看详细信息");
        } else if (qrySuccNum!=0&&qryFailNum!=0&&retAtsTrans.getWrittenRdCount()==0) {
            retAtsTrans.writeRespCode("0");
            retAtsTrans.writeRespInfo("部分查询成功");
        }
        retAtsTrans.writeEnd();
        return retAtsTrans;

    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actArea = p_req7515.actArea;
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        String date = Format.Date8Format.format(new Date());
        p_req7516.dateFrom = date;
        p_req7516.dateTo = date;
        return d_7516_HisTrans(p_req7516);
    }

    public void qryHisTrans(Date fromDate,Date endDate,Req7516HisTrans p_req7516,RetAtsTrans retAtsTrans)throws Exception{
        int tmpNowReadNum = 0;
        int tmpTotalNum =0;
        int pageNum = getBankConfig().getValueAsInt("pageNum")==-1?20:getBankConfig().getValueAsInt("pageNum");
        WriteBankLogLn("----------------------------------------------------------------------------------\r\n");
        do{
            WriteBankLogLn2(String.format("开始查询账号：[%s]，起始日期：[%s]，结束日期:[%s]，起始笔数：[%s]的交易明细",
                    p_req7516.actNum, Format.Date8Format.format(fromDate), Format.Date8Format.format(endDate) ,
                    tmpNowReadNum));
            XmlTextWriter xmlWriter = new XmlTextWriter();
            HFRCB01Header header = new HFRCB01Header();
            header.reqTime =new Date();
            header.serialNo = getBatchID(header.reqTime);
            header.trsCode = "B2EACTransQry";
            writeCommonHeader(xmlWriter,header);
            xmlWriter.writeStartElement("Body");
//                    AcNo	账号	String(32)	M
            xmlWriter.writeElementString("AcNo",p_req7516.actNum );
//                    BeginDate	查询开始日期	String(32)	M
            xmlWriter.writeElementString("BeginDate", Format.Date8Format.format(fromDate));
//                    EndDate	查询结束日期	String(8)	M
            xmlWriter.writeElementString("EndDate",  Format.Date8Format.format(endDate));
//                    CurrentIndex	起始记录数	String(8)	M	首次查询送0
            xmlWriter.writeElementString("CurrentIndex",tmpNowReadNum+"" );
//                    QueryCount	查询条数	String(8)	M
            xmlWriter.writeElementString("QueryCount",""+pageNum );

            xmlWriter.writeEndDocument();
            String[] result = sendToBank(xmlWriter.toXmlString(),false);
            if(result[0].length()==0){
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(result[1].trim(),tmpSbMsg);
                if(tmpBkReader!=null){
                    String rsp_no = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                    String rsp_msg = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                    if ("000000".equals(rsp_no)) {
                        WriteBankLogLn(String.format("查询账号：[%s]，起始日期：[%s]，结束日期:[%s]，起始笔数：[%s] 的交易明细成功\r\n",
                                p_req7516.actNum, Format.Date8Format.format(fromDate), Format.Date8Format.format(endDate) ,
                                tmpNowReadNum));
                        if(tmpTotalNum==0){
                            tmpTotalNum = Integer.valueOf(tmpBkReader.getFirstText("/Message/Body/TotalNum"));
                        }
                        while (tmpBkReader.read("/Message/Body/List/Map")){
                            XElement readXElement = tmpBkReader.readedXElement;
                            RetAtsTransDetail detail = new RetAtsTransDetail();
                            detail.actNum = p_req7516.actNum;
//                                    HostJnlNo	主机流水号	String(15)	M
                            detail.bnkSeqNo = readXElement.getSingleTextNotNull("HostJnlNo").trim();
//                                    TrsDate	交易发生日期	String(8)	M
                            detail.tranDate =DateHelper.convertD8toD10(readXElement.getSingleTextNotNull("TrsDate").trim());
                            detail.valueDate = detail.tranDate;
//                                    TrsTime	交易发生时间	String(6)	M
                            detail.tranTime = detail.valueDate+ " " + DateHelper.getFormat8Time(readXElement.getSingleTextNotNull("TrsTime").trim());
//                                    Currency	货币代号	String(3)	M
                            detail.cur = convertCurToATS(readXElement.getSingleTextNotNull("Currency").trim());//币种
//                                    Amount	交易金额	Double(15,2)	M
                            detail.tranAmt = readXElement.getSingleTextNotNull("Amount").trim();//交易金额
//                                    DCFlag	借贷标志	String(1)	M
                            String cdFlag = readXElement.getSingleTextNotNull("DCFlag").trim();//借贷标志 D--借C--贷
                            if (cdFlag.equals("C")) {
                                if(detail.tranAmt.indexOf("-")>=0) {
                                    detail.cdFlag = "1";
                                    detail.tranAmt = detail.tranAmt.substring(1);
                                }else{
                                    detail.cdFlag = "2";
                                }
                            } else if(cdFlag.equals("D")) {
                                if(detail.tranAmt.indexOf("-")>=0){
                                    detail.cdFlag = "2";
                                    detail.tranAmt = detail.tranAmt.substring(1);
                                }else{
                                    detail.cdFlag = "1";
                                }
                            }else {
                                throw new Exception("借贷标志( " + cdFlag + ")无法识别，请与银行核对");
                            }

//                                    Balance	余额	Double(15,2)	M
                            detail.accBal = readXElement.getSingleTextNotNull("Balance").trim();//账户余额
//                                    Remark	付款用途	String(60)	M
                            String note = readXElement.getSingleTextNotNull("Remark").trim();
                            detail.abstr = pickupAbstr(note);
                            detail.usage = note;
//                                    PayerAcName	付款人名称	String(120)	M
//                                    PayerBankName	付款人行号	String(120)	M
//                                    PayerAcNo	付款人账号	String(60)	M
//                                    PayeeAcName	收款人名称	String(120)	C
//                                    PayeeBankName	收款人行号	String(120)	C
//                                    PayeeAcNo	收款人账号	String(60)	C
                            if("1".equals(detail.cdFlag)){
                                detail.recAccNum = readXElement.getSingleTextNotNull("PayeeAcNo").trim();
                                detail.recAccName = readXElement.getSingleTextNotNull("PayeeAcName").trim();
                                detail.recAccBank = readXElement.getSingleTextNotNull("PayeeBankName").trim();
                            }else {
                                detail.recAccNum = readXElement.getSingleTextNotNull("PayerAcNo").trim();
                                detail.recAccName = readXElement.getSingleTextNotNull("PayerAcName").trim();
                                detail.recAccBank = readXElement.getSingleTextNotNull("PayerBankName").trim();
                            }
                            retAtsTrans.writeRetDetail(detail);
                        }
                        tmpNowReadNum=tmpNowReadNum+pageNum;
                        qrySuccNum++;
                    }else{
                        WriteBankLogLn(String.format("查询账号：[%s]，起始日期：[%s]，结束日期:[%s]，起始笔数：[%s]的交易明细失败\r\n",
                                p_req7516.actNum, Format.Date8Format.format(fromDate), Format.Date8Format.format(endDate) ,
                                tmpNowReadNum));
                        WriteBankLogLn(rsp_msg);
                        tmpNowReadNum=tmpNowReadNum+pageNum;
                        qryFailNum++;
                    }
                }else{
                    WriteBankLogLn(String.format("查询账号：[%s]，起始日期：[%s]，结束日期:[%s]，起始笔数：[%s]的交易明细失败\r\n",
                            p_req7516.actNum, Format.Date8Format.format(fromDate), Format.Date8Format.format(endDate) ,
                            tmpNowReadNum));
                    WriteBankLogLn(tmpSbMsg.toString());
                    tmpNowReadNum=tmpNowReadNum+pageNum;
                    qryFailNum++;
                }
            }else{
                WriteBankLogLn(String.format("查询账号：[%s]，起始日期：[%s]，结束日期:[%s]，起始笔数：[%s]的交易明细失败\r\n",
                        p_req7516.actNum, Format.Date8Format.format(fromDate), Format.Date8Format.format(endDate) ,
                        tmpNowReadNum));
                WriteBankLogLn( result[1]);
                tmpNowReadNum=tmpNowReadNum+pageNum;
                qryFailNum++;
            }
            WriteBankLogLn("----------------------------------------------------------------------------------\r\n");
        } while (tmpNowReadNum<tmpTotalNum);
    }
}
